﻿using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace CloseDisplay1
{
    public class LockScreenIdleMonitor : IDisposable
    {
        /// <summary>
        /// 中文释义：键盘鼠标空闲检测定时器
        /// </summary>
        private Timer idleTimer;

        /// <summary>
        /// 中文释义：键盘鼠标空闲秒数
        /// </summary>
        private int idleSeconds = 0;

        /// <summary>
        /// 中文释义：键盘鼠标空闲事件
        /// </summary>
        public event EventHandler IdlHandle;

        /// <summary>
        /// 中文释义：键盘鼠标空闲秒数变化事件
        /// </summary>
        public event EventHandler<int> IdlTick;

        /// <summary>
        /// 中文释义：键盘鼠标空闲阈值，单位秒
        /// </summary>
        public int Threshold { get; set; } = 10;  //空闲10秒 

        /// <summary>
        /// 中文释义：系统锁屏/解锁监听工具类
        /// </summary>
        private LockScreenWatcher watcher = new LockScreenWatcher();

        public LockScreenIdleMonitor()
        {
            idleTimer = new Timer();
            idleTimer.Interval = 1000; // 每秒检查一次
            idleTimer.Tick += IdleTimer_Tick;

            watcher.OnLock += () =>
            {
                Tools.TurnOffMonitor(); // 锁屏时关闭显示器
                Start(); // 锁屏时开始监控
            };

            watcher.OnUnlock += () =>
            {
                Stop(); // 解锁时停止监控
            };
        }

        [StructLayout(LayoutKind.Sequential)]
        struct LASTINPUTINFO
        {
            public uint cbSize;
            public uint dwTime;
        }

        [DllImport("user32.dll")]
        private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);

        private int GetIdleSeconds()
        {
            LASTINPUTINFO lii = new LASTINPUTINFO();
            lii.cbSize = (uint)Marshal.SizeOf(lii);
            if (!GetLastInputInfo(ref lii)) return 0;

            long idleTime = Environment.TickCount - lii.dwTime;
            return (int)(idleTime / 1000);
        }

        public void Start()
        {
            idleSeconds = 0;
            idleTimer.Start();
        }

        public void Stop()
        {
            idleTimer.Stop();
        }

        private void IdleTimer_Tick(object sender, EventArgs e)
        {
            //if (watcher.IsLocked)
            {
                int idleSec = GetIdleSeconds();

                idleSeconds = idleSec; // 键盘鼠标活动，重置计数
                IdlTick?.Invoke(this, idleSeconds);

                // 鼠标键盘空闲事件（鼠标键盘未达到阈值时触发）
                if (idleSeconds == Threshold)
                {
                    IdlHandle?.Invoke(this, EventArgs.Empty);
                }
            }
        }

        public void Dispose()
        {
            idleTimer?.Dispose();
            Stop();
        }
    }
}